using vue0701.Application.Common.interfaces;
using vue0701.Domain.Entities.App;
using vue0701.Domain.Reposoitiories;

namespace vue0701.Application.Services;

public class AuthService
{
    private readonly IRepository<AppUser> _userRepo;
    private readonly IPasswordHasher _passwordHasher;

    public AuthService(IRepository<AppUser> userRepo, IPasswordHasher passwordHasher)
    {
        _userRepo = userRepo;
        _passwordHasher = passwordHasher;
    }

    // 注册
    public async Task<AppUser> RegisterAsync(string userName, string password)
    {
        var users = await _userRepo.GetAllAsync();
        if (users.Any(u => u.UserName == userName))
            throw new Exception("用户名已存在");

        var salt = _passwordHasher.GenerateSalt();
        var hash = _passwordHasher.HashPassword(password, salt);
        var user = new AppUser(userName, hash, salt);
        await _userRepo.CreateAsync(user);
        return user;
    }

    // 登录
    public async Task<AppUser?> LoginAsync(string userName, string password)
    {
        var users = await _userRepo.GetAllAsync();
        var user = users.FirstOrDefault(u => u.UserName == userName);
        if (user == null)
            return null;
        var isValid = _passwordHasher.VerifyHashedPassword(user.Password, user.Salt, password);
        return isValid ? user : null;
    }
}
